<template>
  <div class="jobs-page">
    <!-- 顶部搜索框 -->
    <div class="search-section">
      <div class="search-wrapper">
        <el-input
          v-model="searchText"
          placeholder="搜索职位 / 公司 / 关键词"
          size="large"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSearch"
              :loading="esLoading"
            >搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 主要内容区域：左侧职位列表 + 右侧职位详情 -->
    <div class="jobs-container">
      <!-- 左侧职位列表 -->
      <div class="jobs-list">
        <div
          v-for="job in jobList"
          :key="job.id"
          class="job-card"
          :class="{ active: selectedJob?.id === job.id }"
          @click="selectJob(job)"
        >
          <div class="job-header">
            <div class="job-title">{{ job.title }}</div>
            <div class="job-salary">{{ job.salary }}</div>
          </div>
          <div class="job-tags">
            <span v-if="job.experience" class="tag">{{ job.experience }}</span>
            <span v-if="job.education" class="tag">{{ job.education }}</span>
            <span v-for="skill in job.skills" :key="skill" class="tag">{{ skill }}</span>
            <span v-if="job.remote === false" class="tag no-remote">不接受居家办公</span>
          </div>
          <div class="job-footer">
            <span class="company-name">{{ job.company }}</span>
            <span class="separator">·</span>
            <span class="location">{{ job.location }}</span>
          </div>
        </div>
        <div v-if="jobList.length === 0" class="empty-state">
          <p>暂无职位信息</p>
        </div>
      </div>

      <!-- 右侧职位详情 -->
      <div class="job-detail">
        <div v-if="selectedJob" class="detail-content">
          <!-- 职位头部信息 -->
          <div class="detail-header">
            <div class="detail-title-row">
              <h1 class="detail-title">{{ selectedJob.title }}</h1>
              <div class="detail-salary">{{ selectedJob.salary }}</div>
            </div>
            <div class="detail-meta">
              <span>{{ selectedJob.location }}</span>
              <span v-if="selectedJob.experience">{{ selectedJob.experience }}</span>
              <span v-if="selectedJob.education">{{ selectedJob.education }}</span>
            </div>
            <div class="detail-actions">
              <el-button type="primary" size="large">立即沟通</el-button>
              <el-button size="large">收藏</el-button>
            </div>
            <div class="detail-share">
              <a href="#" class="share-link">微信扫码分享</a>
              <span class="separator">|</span>
              <a href="#" class="share-link">举报</a>
            </div>
          </div>

          <!-- 职位描述 -->
          <div class="detail-section" v-if="selectedJob.description || selectedJob.skills">
            <h2 class="section-title">职位描述</h2>
            <div v-if="selectedJob.description" class="description-text">
              <p v-for="(para, index) in formatParagraphs(selectedJob.description)" :key="index">
                {{ para }}
              </p>
            </div>
            <div v-if="selectedJob.skills && selectedJob.skills.length > 0" class="skill-tags">
              <span
                v-for="skill in selectedJob.skills"
                :key="skill"
                class="skill-tag"
                @click="handleSkillClick(skill)"
              >{{ skill }}</span>
            </div>
          </div>

          <!-- 任职资格 -->
          <div class="detail-section" v-if="formattedQualifications.length > 0">
            <h2 class="section-title">任职资格</h2>
            <ol class="qualification-list">
              <li v-for="(qual, index) in formattedQualifications" :key="index">{{ qual }}</li>
            </ol>
          </div>

          <!-- 职位要求 -->
          <div class="detail-section" v-if="formattedRequirements.length > 0">
            <h2 class="section-title">职位要求</h2>
            <ol class="requirement-list">
              <li v-for="(req, index) in formattedRequirements" :key="index">{{ req }}</li>
            </ol>
          </div>
        </div>
        <div v-else class="empty-detail">
          <p>请从左侧选择一个职位查看详情</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getJobList } from '../../api/job'
import { esSearch } from '../../api/search'
import { ElMessage } from 'element-plus'

export default {
  name: 'JobsView',
  data() {
    return {
      searchText: '',
      jobList: [],
      selectedJob: null,
      useESSearch: true,  // 是否使用 ES 搜索
      esLoading: false,   // ES 搜索加载状态
    }
  },
  mounted() {
    this.fetchJobs()
  },
  computed: {
    // 格式化后的职位要求
    formattedRequirements() {
      if (!this.selectedJob) {
        return []
      }
      return this.formatRequirements(this.selectedJob.requirements)
    },
    // 格式化后的任职资格
    formattedQualifications() {
      if (!this.selectedJob) {
        return []
      }
      return this.formatRequirements(this.selectedJob.qualifications || this.selectedJob.description)
    },
  },
  methods: {
    async fetchJobs() {
      // 如果有搜索关键词且启用 ES，优先使用 ES 搜索
      if (this.searchText.trim() && this.useESSearch) {
        await this.fetchJobsFromES()
      } else {
        await this.fetchJobsFromAPI()
      }
    },
    
    // 使用 ES 搜索职位
    async fetchJobsFromES() {
      this.esLoading = true
      try {
        const response = await esSearch({
          index: 'job_index',
          keyword: this.searchText.trim(),
          page: 1,
          size: 20
        })
        
        if (response.code === 200 && response.data?.docs) {
          // 将 ES 返回的数据转换为职位列表格式
          this.jobList = response.data.docs.map(doc => {
            const jobData = {
              id: doc.data.id || doc.id,
              ...doc.data,
              // 格式化职位要求：如果是字符串，转换为数组
              requirements: this.formatRequirements(doc.data.requirements),
              // 格式化任职资格：如果是字符串，转换为数组
              qualifications: this.formatRequirements(doc.data.description),
              // 格式化技能：如果是字符串，转换为数组
              skills: this.formatSkills(doc.data.requirements || doc.data.description || ''),
              // 格式化其他字段
              salary: doc.data.salary_range || doc.data.salary || '面议',
              experience: doc.data.experience_requirement || doc.data.experience || '不限',
              education: doc.data.education_requirement || doc.data.education || '不限',
              location: doc.data.work_city || doc.data.location || '未知',
              company: doc.data.company_name || doc.data.company || '未知公司'
            }
            return jobData
          })
          
          if (this.jobList.length > 0) {
            ElMessage.success(`找到 ${response.data.total} 个相关职位`)
            this.selectJob(this.jobList[0])
          } else {
            ElMessage.info('未找到相关职位，显示推荐职位')
            this.jobList = this.getMockJobs()
            this.selectJob(this.jobList[0])
          }
        } else {
          // ES 搜索失败，降级到模拟数据
          this.jobList = this.getMockJobs()
          this.selectJob(this.jobList[0])
        }
      } catch (error) {
        console.error('ES 搜索失败:', error)
        // 降级到模拟数据
        this.jobList = this.getMockJobs()
        if (this.jobList.length > 0) {
          this.selectJob(this.jobList[0])
        }
      } finally {
        this.esLoading = false
      }
    },
    
    // 使用 API 获取职位列表
    async fetchJobsFromAPI() {
      try {
        const params = {}
        if (this.searchText) {
          params.search = this.searchText
        }
        const res = await getJobList(params)
        // 兼容多种返回结构
        const list = Array.isArray(res) ? res : (res?.data || [])
        this.jobList = list.length > 0 ? list : this.getMockJobs()
        
        // 默认选中第一个职位
        if (this.jobList.length > 0 && !this.selectedJob) {
          this.selectJob(this.jobList[0])
        }
      } catch (e) {
        console.error('获取职位列表失败:', e)
        // 如果接口失败，使用模拟数据
        this.jobList = this.getMockJobs()
        if (this.jobList.length > 0) {
          this.selectJob(this.jobList[0])
        }
      }
    },
    
    selectJob(job) {
      // 确保职位要求格式正确
      if (job && job.requirements) {
        job.requirements = this.formatRequirements(job.requirements)
      }
      if (job && job.qualifications) {
        job.qualifications = this.formatRequirements(job.qualifications)
      }
      this.selectedJob = job
    },
    handleSearch() {
      this.fetchJobs()
    },
    handleSkillClick(skill) {
      this.searchText = skill
      this.handleSearch()
    },
    // 格式化职位要求/任职资格：将字符串转换为数组
    formatRequirements(req) {
      if (!req) {
        return []
      }
      
      // 如果已经是数组，直接返回（过滤空项）
      if (Array.isArray(req)) {
        return req
          .map(item => typeof item === 'string' ? item.trim() : String(item).trim())
          .filter(item => item && item.length > 0)
      }
      
      // 如果是字符串，尝试按多种方式分割
      if (typeof req === 'string') {
        const text = req.trim()
        if (!text) {
          return []
        }
        
        // 方法1：如果包含数字序号模式（1. 2. 3. 或 1、2、3、），按序号分割
        const numberedPattern = /(\d+)[\.、]\s*([^0-9]+?)(?=\d+[\.、]|$)/g
        const numberedMatches = [...text.matchAll(numberedPattern)]
        if (numberedMatches.length > 0) {
          const items = numberedMatches.map(match => match[2].trim()).filter(item => item)
          if (items.length > 0) {
            return items
          }
        }
        
        // 方法2：按换行符分割，过滤空行
        const lines = text.split(/\n+/).map(line => line.trim()).filter(line => line)
        if (lines.length > 1) {
          // 移除每行的序号前缀（如果存在）
          return lines.map(line => line.replace(/^\d+[\.、]\s*/, '')).filter(line => line)
        }
        
        // 方法3：如果只有一行，尝试按分号或句号分割
        if (lines.length === 1) {
          const singleLine = lines[0]
          
          // 按分号分割
          if (singleLine.includes('；') || singleLine.includes(';')) {
            return singleLine.split(/[；;]/).map(s => s.trim()).filter(s => s)
          }
          
          // 按句号分割（保留完整句子）
          if (singleLine.includes('。')) {
            const sentences = singleLine.split(/[。]/).map(s => s.trim()).filter(s => s)
            // 如果分割后句子太短，可能是误分割，返回原文本
            if (sentences.length > 1 && sentences.every(s => s.length > 10)) {
              return sentences
            }
          }
          
          // 如果都不行，返回整行（但检查长度，避免显示过长的单行文本）
          if (singleLine.length > 200) {
            // 对于超长文本，尝试按句号强制分割
            const forcedSplit = singleLine.split(/[。！？]/).map(s => s.trim()).filter(s => s && s.length > 5)
            return forcedSplit.length > 0 ? forcedSplit : [singleLine]
          }
          
          return [singleLine]
        }
        
        return []
      }
      
      return []
    },
    // 格式化技能：从职位要求或描述中提取技能关键词
    formatSkills(text) {
      if (!text) {
        return []
      }
      
      const skillKeywords = [
        'Java', 'Python', 'JavaScript', 'TypeScript', 'Vue', 'React', 'Angular',
        'Node.js', 'Spring', 'Spring Boot', 'Spring Cloud', 'MyBatis', 'Hibernate',
        'MySQL', 'PostgreSQL', 'MongoDB', 'Redis', 'Elasticsearch',
        'Docker', 'Kubernetes', 'Kafka', 'RabbitMQ',
        'Golang', 'Go', 'C++', 'C#', '.NET',
        'Linux', 'Git', 'CI/CD', '微服务', '分布式', '高并发',
        '前端开发', '后端开发', '全栈开发', '移动开发', 'iOS', 'Android'
      ]
      
      const skills = []
      const textStr = typeof text === 'string' ? text : JSON.stringify(text)
      
      for (const keyword of skillKeywords) {
        if (textStr.includes(keyword) && !skills.includes(keyword)) {
          skills.push(keyword)
        }
      }
      
      return skills.length > 0 ? skills : []
    },
    // 格式化段落：将长文本按段落分割
    formatParagraphs(text) {
      if (!text) {
        return []
      }
      const textStr = typeof text === 'string' ? text : String(text)
      // 按双换行符或句号+换行符分割段落
      const paragraphs = textStr.split(/\n\s*\n|。\s*\n/).map(p => p.trim()).filter(p => p)
      return paragraphs.length > 0 ? paragraphs : [textStr]
    },
    // 模拟数据（当后端接口未准备好时使用）
    getMockJobs() {
      return [
        {
          id: 1,
          title: '后端开发',
          salary: '14-22K',
          experience: '5-10年',
          education: '大专',
          skills: ['Golang', 'Java', 'C++', 'Hibernate', '团队管理经验', '架构设计经验', 'Python'],
          company: '辰光幻影',
          location: '北京·朝阳区·三里屯',
          remote: false,
          qualifications: [
            '负责核心业务模块的编码实现，参与系统架构设计',
            '参与需求分析，优化系统性能和架构',
            '与前端团队协作，完成接口对接',
            '负责技术文档编写和维护',
          ],
          requirements: [
            '5年以上Java开发经验，熟悉分布式、高并发系统架构',
            '熟练掌握Spring Cloud、Kafka等中间件',
            '熟悉MySQL、Redis等数据库和缓存技术',
            '对新技术的敏感度强，了解物联网、大数据等相关技术',
          ],
        },
        {
          id: 2,
          title: '一线大厂+双休+试用期全薪 Java开发工程师',
          salary: '17-20K',
          experience: '3-5年',
          education: '本科',
          skills: ['Java', 'SpringCloud', 'Kafka', 'MySQL'],
          company: '纬创软件',
          location: '北京·朝阳区·望京',
          remote: false,
          qualifications: [
            '参与核心业务系统的设计与开发',
            '优化系统性能，提升用户体验',
            '编写高质量代码，进行代码审查',
          ],
          requirements: [
            '3年以上Java开发经验',
            '熟悉Spring Cloud微服务架构',
            '熟悉MySQL数据库设计和优化',
          ],
        },
        {
          id: 3,
          title: 'java全栈开发工程师',
          salary: '10-13K',
          experience: '1-3年',
          education: '本科',
          skills: ['Java', 'Vue', 'React', 'MySQL'],
          company: '带得科技',
          location: '北京·海淀区·中关村',
          remote: false,
          qualifications: [
            '负责前后端开发工作',
            '参与产品需求讨论和技术方案设计',
            '维护和优化现有系统',
          ],
          requirements: [
            '1年以上全栈开发经验',
            '熟悉Java后端开发和Vue/React前端开发',
            '具备良好的学习能力',
          ],
        },
      ]
    },
  },
}
</script>

<style scoped>
.jobs-page {
  min-height: calc(100vh - 64px);
  background: #f5f5f5;
  padding-bottom: 24px;
}

/* 顶部搜索区域 */
.search-section {
  background: #fff;
  padding: 24px 0;
  border-bottom: 1px solid #e5e5e5;
}

.search-wrapper {
  width: 80%;
  margin: 0 auto;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e5e5 inset;
}

/* 主要内容容器 */
.jobs-container {
  width: 80%;
  margin: 24px auto 0 auto;
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

/* 左侧职位列表 */
.jobs-list {
  width: 400px;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.job-card {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s;
}

.job-card:hover {
  background: #fafafa;
}

.job-card.active {
  background: #f0fffb;
  border-left: 3px solid #00c293;
}

.job-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.job-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.job-salary {
  color: #ff4d4f;
  font-weight: 700;
  font-size: 16px;
  margin-left: 12px;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.tag {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 3px;
}

.tag.no-remote {
  color: #ff4d4f;
  background: #fff1f0;
}

.job-footer {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  font-size: 13px;
}

.company-name {
  color: #333;
  font-weight: 500;
}

.separator {
  color: #ccc;
}

.location {
  color: #666;
}

.empty-state {
  padding: 40px;
  text-align: center;
  color: #999;
}

/* 右侧职位详情 */
.job-detail {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  min-height: 600px;
}

.detail-content {
  height: 100%;
}

.detail-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
  margin-bottom: 24px;
}

.detail-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.detail-title {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0;
  flex: 1;
}

.detail-salary {
  color: #ff4d4f;
  font-weight: 700;
  font-size: 24px;
  margin-left: 16px;
}

.detail-meta {
  display: flex;
  gap: 16px;
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.detail-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.detail-share {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  font-size: 13px;
}

.share-link {
  color: #999;
  text-decoration: none;
  cursor: pointer;
}

.share-link:hover {
  color: #00c293;
}

/* 职位描述部分 */
.detail-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-bottom: 16px;
}

.skill-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 24px;
}

.skill-tag {
  padding: 6px 16px;
  background: #f5f5f5;
  border-radius: 4px;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.skill-tag:hover {
  background: #00c293;
  color: #fff;
}

.qualification-list,
.requirement-list {
  padding-left: 24px;
  color: #333;
  line-height: 2;
  margin: 0;
}

.qualification-list li,
.requirement-list li {
  margin-bottom: 12px;
  padding-left: 8px;
  font-size: 15px;
}

.description-text {
  color: #666;
  line-height: 1.8;
  margin-bottom: 20px;
}

.description-text p {
  margin-bottom: 12px;
  font-size: 15px;
}

.empty-detail {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
  font-size: 16px;
}

/* 滚动条样式 */
.jobs-list::-webkit-scrollbar {
  width: 6px;
}

.jobs-list::-webkit-scrollbar-track {
  background: #f5f5f5;
}

.jobs-list::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.jobs-list::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>
